<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3_react生命周期(新)</title>
</head>
<style>
  .list{
    width: 300px;
    height: 150px;
    background-color: aqua;
    overflow: auto;
  }
  .new{
    height: 30px;
  }
</style>
<body>
  <!-- 准备好一个“容器” -->
  <div id="test"></div>
  <!-- 引入react核心库 -->
  <script type="text/javascript" src="../js/react.development.js"></script>
  <!-- 引入react-dom 用于支持react操作DOM -->
  <script type="text/javascript" src="../js/react-dom.development.js"></script>
  <!-- 引入babel 用于将jsx转换为js -->
  <script type="text/javascript" src="../js/babel.min.js"></script>

  <script type="text/babel">  // 此处一定要写babel

    // 1. 创建组件
    class Life extends React.Component {

      state = {newArr: []}

       // 组件挂载完毕的钩子
       componentDidMount() {
        setInterval(() => {
          //获取原状态
          const {newArr} = this.state
          //模拟一条新闻
          const news = '新闻' + (newArr.length+1)
          //更新。一条状态
          this.setState({newArr: [news, ...newArr]})
        }, 1000)
      }

      // 在更新之前获取快照
      getSnapshotBeforeUpdate(){
        console.log('Life---getSnapshotBeforeUpdate', this.refs.list.scrollHeight, this.refs)
        return this.refs.list.scrollHeight
      }

      // 组件更新完毕的钩子
      componentDidUpdate(preProps, preState, snapshotValue) {
        console.log('Life---componentDidUpdate', preProps, preState, snapshotValue)
        this.refs.list.scrollTop += this.refs.list.scrollHeight - snapshotValue
      }


      // 初始化渲染、状态更新之后
      render() {
        console.log('Life---render')
        return (
          <div className="list" ref="list">
            {
              this.state.newArr.map((n, index) => {
                return <div key={index} className="news">{n}</div>
              })
            }
          </div>
        )
      }
    }

    // 2. 渲染虚拟组件到页面
    ReactDOM.render(<Life/>, document.getElementById('test'))

  </script>
</body>

</html>